package yx.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 描述：文件读取工具类
 * 作成者：wanghairui
 */
public class FileUtils {

	/**
	 * 获取文件字节
	 * @param infile
	 * @return
	 */
	public static byte[] readFile(File infile) {
		try {
			if (infile.length() == 0) {
				return new byte[] {};
			}
			byte[] buf = new byte[8 * 1024];
			FileInputStream fileis = null;
			ByteArrayOutputStream byteos = null;
			try {
				fileis = new FileInputStream(infile);
				byteos = new ByteArrayOutputStream(new Long(infile.length()).intValue());
				int len = 0;
				while ((len = fileis.read(buf)) != -1) {
					byteos.write(buf, 0, len);
				}
				return byteos.toByteArray();
			} finally {
				try {
					if (fileis != null) {
						fileis.close();
					}
					if (byteos != null) {
						byteos.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}
	
	/**
	 * 获取文件字节
	 * @param fis
	 * @return
	 */
	public static byte[] readFile(InputStream fis) {
		try {
			if (fis == null) {
				return new byte[] {};
			}
			byte[] buf = new byte[8 * 1024];
			ByteArrayOutputStream baos = null;
			try {
				baos = new ByteArrayOutputStream();
				int len = 0;
				while ((len = fis.read(buf)) != -1) {
					baos.write(buf, 0, len);
				}
				return baos.toByteArray();
			} finally {
				try {
					if (fis != null) {
						fis.close();
					}
					if (baos != null) {
						baos.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}
	
	/**
	 * 获取文件字节
	 * @param filename
	 * @return
	 */
	public static byte[] readFile(String fullName) {
		return readFile(new File(fullName));
	}
	
	/**
	 * 解析一个xml文档
	 * @param fullName
	 * @return
	 */
	/*
    public static Document parseXml2Doc(String fullName) {
        try {
        	if(fullName == null || "".equals(fullName)){
				return null;
        	}
        	byte[] ret = readFile(fullName);
			if (ret == null) {
				return null;
			}
        	InputStream is = new ByteArrayInputStream(ret);
            if(is == null){
                return null;
            }
            try {
            	return XmlUtils.getDocumentBuilder().parse(is);
            } finally {
                if (is != null) {
                	is.close();
                }
            }
        } catch (Exception ex) {
            RuntimeException re =  new RuntimeException("FileUtils.readXmlConfigFile: " + fullName);
            re.initCause(ex);
            throw re;
        }
    }*/

	/**
	 * 测试类
	 * @param args
	 */
	public static void main(String[] args) {
		
	}

}
